<?php

class ExecuteLoop {

	private $executor;
	
	public function __construct($executor) {			
		$this->executor  = $executor;	
	}
	
	public function run() {
		Yii::log('executor started', CLogger::LEVEL_INFO, EXECUTOR_LOG);
 		while (true) {		
			sleep(EXECUTOR_LOOP_INTERVAL);
	 		$status = $this->executor->isOnline();		
			if($status === false) {
				Yii::log('executor is offline ', CLogger::LEVEL_ERROR, EXECUTOR_LOG);
				break;
			}
			
			Yii::log('begin execute tasks', CLogger::LEVEL_INFO, EXECUTOR_LOG);
			$readyTasks = $this->executor->getReadyTasks();	
			Yii::log('process ready tasks, total: '. count($readyTasks), CLogger::LEVEL_INFO, EXECUTOR_LOG);
			
			foreach ($readyTasks as $task) {
				$this->executor->execute($task);
			}
			unset($readyTasks);
			Yii::log('execute tasks successfully', CLogger::LEVEL_INFO, EXECUTOR_LOG);	
 		}
 		Yii::log('executor ended', CLogger::LEVEL_INFO, EXECUTOR_LOG);
	}
}
